/**
 * 
 */
package com.nari.interfaces.decipher.gprs;

import java.util.Date;

import org.apache.mina.core.session.IoSession;

import com.nari.platform.date.CalendarUtils;

/**
 * 会话状态跟踪
 * @author Xiaopeng
 * @date 2014-1-14
 */
public class IoSessionRepeatState {
	//最新更新时间，格式：yyyyMMddHHmmss
	private String lastUpdateTime;
	//剩余可发送次数
	private int remainSentCounter = 3;
	//发送频率(单位：秒)
	private static final int sentFrequency = 20;
	//系统会话
	private IoSession session;
	
	//
	private IoSessionRepeatState(){}
	
	/**
	 * 会话状态实例化
	 * @param session
	 * @return
	 * @author Xiaopeng
	 * @date 2014-1-14
	 */
	public synchronized static IoSessionRepeatState getInstance(IoSession session) {
		if(session != null) {
			IoSessionRepeatState sessionState = new IoSessionRepeatState();
			//设置会话状态的更新时间
			String lastUpdateTime = CalendarUtils.parseDateToString(new Date(), "yyyyMMddHHmmss");
			sessionState.setLastUpdateTime(lastUpdateTime);
			//设置会话信息
			sessionState.setSession(session);
			return sessionState;
		}
		return null;
	}
	
	/**
	 * 检查session会话是否可重新发送指令
	 * @param sessionState
	 * @return
	 * @author Xiaopeng
	 * @date 2014-1-14
	 */
	public synchronized static boolean sessionAvailable(IoSessionRepeatState sessionState) {
		if(sessionState != null) {
			String currentTime = CalendarUtils.parseDateToString(new Date(), "yyyyMMddHHmmss");
			//超过指定时限，即可重新发送指令
			if(Long.valueOf(currentTime) >= Long.valueOf(sessionState.getLastUpdateTime()) + IoSessionRepeatState.sentFrequency) {
				//发送次数限制在指定次数以内，即可重新发送指令
				if(sessionState.getRemainSentCounter() > 0) {
					//最新更新时间
					sessionState.setLastUpdateTime(currentTime);
					//修正剩余可发送次数
					sessionState.setRemainSentCounter(sessionState.getRemainSentCounter() - 1);
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * @return the lastUpdateTime
	 */
	public String getLastUpdateTime() {
		return lastUpdateTime;
	}

	/**
	 * @param lastUpdateTime the lastUpdateTime to set
	 */
	public void setLastUpdateTime(String lastUpdateTime) {
		this.lastUpdateTime = lastUpdateTime;
	}

	/**
	 * @return the remainSentCounter
	 */
	public int getRemainSentCounter() {
		return remainSentCounter;
	}

	/**
	 * @param remainSentCounter the remainSentCounter to set
	 */
	public void setRemainSentCounter(int remainSentCounter) {
		this.remainSentCounter = remainSentCounter;
	}

	/**
	 * @return the sentFrequency
	 */
	public int getSentFrequency() {
		return sentFrequency;
	}

	/**
	 * @return the session
	 */
	public IoSession getSession() {
		return session;
	}

	/**
	 * @param session the session to set
	 */
	public void setSession(IoSession session) {
		this.session = session;
	}
	
}
